package com.rocching.easychat.adapter;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.rocching.easychat.R;
import com.rocching.easychat.core.UserIdentityContext;
import com.rocching.easychat.model.SearchUserModel;
import com.rocching.easychat.util.AppUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class SearchFriendListAdapter extends BaseAdapter {
    private List<SearchUserModel> list;
    private final Context context;

    public SearchFriendListAdapter(Context context) {
        this.context = context;
        list = new ArrayList<>();
    }

    public void update(List<SearchUserModel> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        SearchUserModel model = list.get(position);
        if (Objects.isNull(model)) {
            return 0;
        } else {
            return model.getId();
        }
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        SearchFriendListHolder holder = null;
        if (view == null) {
            view = LayoutInflater.from(context).inflate(R.layout.fragment_search_friend_list_item, null);
            holder = new SearchFriendListHolder(view);
            view.setTag(holder);
        } else {
            holder = (SearchFriendListHolder) view.getTag();
        }
        SearchUserModel model = list.get(position);
        if (!Objects.isNull(model)) {
            holder.update(model);
        }
        return view;
    }

    public static class SearchFriendListHolder {
        private final View view;
        private final ImageView friendPhoto;
        private final TextView friendName;
        private final TextView statusName;

        public SearchFriendListHolder(View view) {
            this.view = view;

            friendPhoto = view.findViewById(R.id.friend_photo);
            friendName = view.findViewById(R.id.friend_name);
            statusName = view.findViewById(R.id.status_name);
        }

        public void update(SearchUserModel model) {
            model.setStatusName(AppUtil.getStatusName(view.getContext(), model.getStatus(), model.getId()));
            friendName.setText(model.getName());
            statusName.setText(model.getStatusName());
            Uri uri = AppUtil.getUserPhotoUri(model.getPhoto());
            if (uri != null) {
                Glide.with(view).load(uri).placeholder(R.drawable.loading).into(friendPhoto);
            }
        }
    }
}
